﻿using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using TrackSystem.Entities.Data;
using TrackSystem.Entities.Models;
using TrackSystem.EntityFramework.Mapping;

namespace TrackSystem.EntityFramework
{
    public class TkDBContent : IdentityDbContext<User>
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="options"></param>
        public TkDBContent(DbContextOptions<TkDBContent> options) : base(options)
        {
        }


        /// <summary>
        /// 初始化化函数
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 添加映射配置
            modelBuilder.ApplyConfiguration(new EquipMap());
            modelBuilder.ApplyConfiguration(new ChannelMap());
            modelBuilder.ApplyConfiguration(new SensorMap());
            modelBuilder.ApplyConfiguration(new VarMap());
            modelBuilder.ApplyConfiguration(new LogicMap());
            modelBuilder.ApplyConfiguration(new LoopMap());
            modelBuilder.ApplyConfiguration(new AlarmMap());
            modelBuilder.ApplyConfiguration(new SlaveMap());

            // 初始化数据
            modelBuilder.Entity<EquipTable>().HasData(DataSeed.Equips);
            modelBuilder.Entity<ChannelTable>().HasData(DataSeed.Chns);
            modelBuilder.Entity<SensorTable>().HasData(DataSeed.Sensors);
            modelBuilder.Entity<VarTable>().HasData(DataSeed.Vars);
            modelBuilder.Entity<LogicTable>().HasData(DataSeed.Logics);
            modelBuilder.Entity<LoopTable>().HasData(DataSeed.Loops);
            modelBuilder.Entity<SlaveTable>().HasData(DataSeed.Slaves);

            // 初始化角色数据
            modelBuilder.ApplyConfiguration(new RoleConfiguration());
        }

        /// <summary>
        /// 当前数据库中添加数据表，保存单次的数据记录
        /// </summary>
        /// <param name="recName">记录数据表</param>
        public void InsertRecordTable(string recName)
        {
            _ = Database.ExecuteSql($"CREATE TABLE {recName} (Id INT PRIMARY KEY, Name VARCHAR(100));");
        }

        public DbSet<ChannelTable> Channels { get; set; }

        public DbSet<SensorTable> Sensors { get; set; }

        public DbSet<VarTable> Vars { get; set; }

        public DbSet<EquipTable> Equip { get; set; }

        public DbSet<LogicTable> Logic { get; set; }

        public DbSet<LoopTable> Loop { get; set; } 

        public DbSet<AlarmTable> Alarm { get; set; }
        
        public DbSet<SlaveTable> Slave { get; set; }
    }
}
